import os.path

import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from conf import conf
from tools.framework import get_ui_value
from core.constant import *
from module.static_module.parent.model import AdditionModule

matplotlib.use("Agg")

# 设置字体属性，确保中文正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体为SimHei，这是一个支持中文的字体
plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题


class BacktestingVisualizationModel(AdditionModule):
    def __init__(self, master):
        super().__init__(master, Module.BacktestingVisualization)
        # 实体类映射视图类变量数据
        self.equity_file_ls = []  # 净值文件
        self.trade_file_ls = []  # 交易文件
        self.order_file_ls = []  # 订单文件

        # 映射视图类变量数据默认值
        self.equity_file = []  # 净值文件
        self.trade_file = []  # 交易文件
        self.order_file = []  # 订单文件

        # 实体类结构变量
        self.sub_view = None
        self.draw_num = int(conf.AdditionModule.visualization_x_px.value // conf.AdditionModule.k_px.value * conf.AdditionModule.sample_multiple.value)
        self.draw_data: pd.DataFrame = pd.DataFrame([], columns=["value", "close", "cash", "withdrawal"])
        self.draw_data.index.name = "datetime"
        self.trade_data = None
        self.order_data = None

    def sec_init(self):
        # 实体类映射视图类变量数据
        self.equity_file_ls = []  # 净值文件
        self.trade_file_ls = []  # 交易文件
        self.order_file_ls = []  # 订单文件

        from module.addition_module.backtesting_visualization.view import BacktestingVisualizationView
        self.sub_view = BacktestingVisualizationView(self)

    def get_ui_params(self):
        # 获取ui界面的相关参数
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.EquityFile)
        self.equity_file = get_ui_value(values, indices, WidgetCategory.Entry)
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.TradeFile)
        self.trade_file = get_ui_value(values, indices, WidgetCategory.Entry)
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.OrderFile)
        self.order_file = get_ui_value(values, indices, WidgetCategory.Entry)

    def on_ok(self):
        self.get_ui_params()
        # 获取基本信息
        # 读取净值和交易文件
        equity_data: pd.DataFrame = self.master.file_manager.read_csv(self.equity_file)
        if self.trade_file:
            self.trade_data: pd.DataFrame = self.master.file_manager.read_csv(self.trade_file)
        else:
            pass
        if self.order_file:
            self.order_data: pd.DataFrame = self.master.file_manager.read_csv(self.order_file)
        else:
            pass
        # 新增最大回撤字段
        # 计算累计最大值
        cumulative_max = equity_data["value"].cummax()
        # 计算回撤
        withdrawal_sr = 1 - equity_data["value"] / cumulative_max
        # 计算最大回撤
        max_drawdown = withdrawal_sr.max()
        equity_data["withdrawal"] = withdrawal_sr
        # 获取样本数据个数
        sample_num = self.draw_num
        # 从equity_data中取样
        # indices = np.linspace(0, len(equity_data) - 1, sample_num).astype(int)
        indices = np.linspace(0, len(equity_data) - 1, sample_num, endpoint=True, dtype=int)

        equity_data_sampled = equity_data.iloc[indices]
        # 将样本数据组合成绘制用的draw_data
        self.draw_data["value"] = equity_data_sampled["value"] / equity_data_sampled["value"][0] * conf.AdditionModule.ori_value.value  # 缩放至ori_value
        self.draw_data["close"] = equity_data_sampled["close"]
        self.draw_data["cash"] = equity_data_sampled["cash"]
        self.draw_data["withdrawal"] = equity_data_sampled["withdrawal"]
        # 执行视图模块相关函数
        self.sub_view.draw_dynamic_graph()

        pass
